package com.ssy.lingxi.purchase.config.rabbitmq.provider;

import com.ssy.lingxi.purchase.config.rabbitmq.OrderRbbitMqRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 *延时消息生产者
 */
@Slf4j
@Service
public class RabbitMQProvider {

    private final RabbitTemplate rabbitTemplate;
    public RabbitMQProvider(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }


    /**
     *发送延时消息
     */
    public void sendDelayMessage(OrderRbbitMqRequest request, String exchange, String key, long time) {
        log.info("发送时间:{},发送内容:{}", LocalDateTime.now(), request.toString());
        this.rabbitTemplate.convertAndSend(
                exchange,
                key,
                request,
                message -> {
                    //注意这里时间可以使long，而且是设置header
                    message.getMessageProperties().setHeader("x-delay",request.getExpirationTime()-System.currentTimeMillis() - time);
                    return message;
                }
        );
    }
}